package com.skwen.android_room;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.skwen.android_room.bean.Books;
import com.skwen.android_room.dao.BooksDao;

@Database(entities = Books.class, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase sAppDatabase;

    private static String DB_NAME = "app.db";

    abstract BooksDao booksDao();


    //为方便使用，写个单例
    public static AppDatabase getInstance(Context context) {
        if (sAppDatabase == null) {
            synchronized (AppDatabase.class) {
                if (sAppDatabase == null) {
                    sAppDatabase = buildAppDatabase(context);
                }
            }
        }
        return sAppDatabase;
    }

    //获取 AppDatabase
    private static AppDatabase buildAppDatabase(final Context context) {
        return Room
                .databaseBuilder(context.getApplicationContext(), AppDatabase.class, DB_NAME)
                .addCallback(new Callback() {
                    @Override
                    public void onCreate(@NonNull SupportSQLiteDatabase db) {
                        super.onCreate(db);
                        //创建完数据库 插入一些测试数据
                        AppExecutors.getInstance().getDiskIO()
                                .execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        getInstance(context).booksDao().insertBooks(GenerateUtils.getGenerateData().toArray(new Books[0]));
                                    }
                                });
                    }
                })
                .build();
    }
}
